package office.action.person;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Resource;
import office.action.person.form.TripForm;
import office.action.workflow.form.RemindForm;
import office.bo.person.Trip;
import office.bo.system.Department;
import office.service.person.IPersonService;
import office.service.workflow.IRemindService;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import current.security.user.domain.User;
import current.security.user.manager.service.UserManagerService;
import platform.common.action.BaseAction;
import platform.util.DateUtil;

@Namespace("/person")
@ParentPackage("struts-base")
@Controller("tripAction")
@Scope("prototype")
public class TripAction extends BaseAction{
	private static final long serialVersionUID = 1L;
	private String flag;
	private List<TripForm> tripListData = new ArrayList<TripForm>();
	private TripForm tripForm;
	private UserManagerService userManagerService;
	private IRemindService remindService;
	@Resource
	private IPersonService personalServiceImpl;
	
	@Action(value="gotoTrip",results={@Result(location="/pages/person/workflow/tripEdit.jsp")})
	public String gotoTrip(){
		return "success";
	}
	
	@Action(value="gotoTripMenu",results={@Result(location="/pages/person/workflow/tripXml.jsp")})
	public String gotoTripMenu()throws Exception{
		tripForm = personalServiceImpl.getTripFormById(tripForm.getId());
		return "success";
	}
	
	@Action(value="gotoStopTrip",results={@Result(location="/pages/person/workflow/editStopTrip.jsp")})
	public String gotoStopTrip()throws Exception{
		getTripById();
		return "success";
	}
	
	@Action(value="stopTrip")
	public String stopTrip()throws Exception{
		Trip trip = new Trip();
		//获取出差信息
		trip = personalServiceImpl.getTripById(tripForm.getId());
		if(trip != null){
			//验证是否符合结束出差条件，只能操作当前处于的出差当中
			if(DateUtil.between(DateUtil.getDate(), trip.getBeginDate(), trip.getEndDate(), "yyyy-MM-dd HH:mm:ss")){
				//默认当前时间
				if(tripForm.getStopDate()==null || tripForm.getStopDate().equals("")){
					tripForm.setStopDate(DateUtil.getDate());
				}
				//验证之前是否有过提前结束申请并且时间是否早于本次时间
				if(trip.getStopDate()!=null && DateUtil.compareTo(trip.getStopDate(), tripForm.getStopDate(), "yyyy-MM-dd HH:mm:ss") < 0){
					this.getAjaxMessagesJson().setMessage(false, "", "您已经有过一次比当前时间早的提前结束请假变更！请重新选择时间！");
				}else{
					//验证时间是否在出差范围之内
					if(DateUtil.between(tripForm.getStopDate(), trip.getBeginDate(), trip.getEndDate(), "yyyy-MM-dd HH:mm:ss")){
						trip.setStopReson(tripForm.getStopReson());
						trip.setStopDate(tripForm.getStopDate());
						trip.setSumTime(tripForm.getSumTime());
						//以提醒的方式发送给人事经理
						List<User> users = userManagerService.getUserByRole("xzrsjl");
						for (Iterator<User> iterator = users.iterator(); iterator.hasNext();) {
							User user = (User) iterator.next();
							RemindForm r = buildRemindForm(trip.getId().toString(),user.getId(),getUserCname()+" 提前结束了出差！截止日期为："+tripForm.getStopDate());
							remindService.editRemind(r);
						}
						//删除多余的打卡记录
						personalServiceImpl.deleteTimingByTripAndDate(trip.getId().toString(), tripForm.getStopDate());
						this.getAjaxMessagesJson().setMessage(true, "", "已成功结束出差！剩余的出差打卡考勤将被自动删除！");
					}else{
						this.getAjaxMessagesJson().setMessage(false, "", "您结束的时间未在出差范围之内！");
					}
				}
			}else{
				this.getAjaxMessagesJson().setMessage(false, "", "您操作的出差记录不合法，请选择您当前正处于的出差申请当中！");
			}
			
		}
		return RESULT_AJAXJSON;
	}
	
	@Action(value="saveTrip")
	public String saveTrip() throws Exception{
		Trip trip = new Trip();
		try {
			if( tripForm != null && tripForm.getBeginDate() != null ){
				String time = tripForm.getBeginDate().split(" ")[0];
				if(DateUtil.compareTo(time, DateUtil.getDate("yyyy-MM-dd"), "yyyy-MM-dd") < 0){
					this.getAjaxMessagesJson().setMessage(false, "", "编辑失败！申请的开始时间小于当前时间。");
				}else{
					List<TripForm> validateTrip = personalServiceImpl.validateTrip(super.getUserId(), tripForm.getBeginDate());
					if(tripForm != null && (tripForm.getId() == null || tripForm.getId().equals("")) && validateTrip != null && validateTrip.size() > 0){
						this.getAjaxMessagesJson().setMessage(false, "", "编辑失败！在同一时间内不允许存在两次出差申请。");
					}else{
						//modify by xlp
						BeanUtils.copyProperties(trip,tripForm);
						trip.setEntryRole(getUserRoleName());
						Department d = new Department();
						User u = new User();
						d.setId(getUserDepartmentId());
						u.setId(getUserId());
						trip.setDepartment(d);
						trip.setUser(u);
						if(trip != null && trip.getId() != null && trip.getId().equals("")){
							trip.setId(null);
						}
						personalServiceImpl.saveTrip(trip);
						this.getAjaxMessagesJson().setMessage(true, "", "编辑成功");
					}
				}
			}else{
				this.getAjaxMessagesJson().setMessage(false, "", "编辑失败！开始时间不能为空。");
			}
		} catch (Exception e) {
			log.error("", e);
		} 
		return RESULT_AJAXJSON;
	}
	
	@Action(value="getTripByUid",results={@Result(location="/pages/person/workflow/trip.jsp")})
	public String getTripByUid()throws Exception{
		tripForm = new TripForm();
		tripForm.setEntryUserId(getUserId());
		tripForm.setCheckRole(getUserRoleName());
		tripForm.setDeptId(getUserDepartmentId());
		tripForm.setCompanyId(getUserCompanyId());
		tripForm.setRoleDFlag(getRoleDFlag());
		tripListData = personalServiceImpl.getListTrip(tripForm);
		return "success";
	}
	
	private Integer year = Integer.valueOf(DateUtil.getCurrentYear());
	
	private Integer month = Integer.valueOf(DateUtil.getCurrentMonth());
	
	private Integer state = 3;
	
	@Action(value="getAllTrip",results={@Result(location="/pages/person/workflow/tripAll.jsp")})
	public String getAllTrip()throws Exception{
		Integer bstate = null;
		Integer lstate = null;
		if(state == 1){
			bstate = -1;
			lstate = 0;
		}else if(state == 2){
			bstate = 1;
			lstate = 1;
		}else if(state == 3){
			bstate = 100;
			lstate = 110;
		}
		tripListData = personalServiceImpl.getAllTrip(year,month,bstate,lstate);
		return "success";
	}
	
	@Action(value="deleteById")
	public String deleteById(){
		personalServiceImpl.deleteById(tripForm.getId());
		this.getAjaxMessagesJson().setMessage(true, "", "删除成功");
		return RESULT_AJAXJSON;
	}
	
	@Action(value="getTripById",results={@Result(location="/pages/person/workflow/tripEdit.jsp")})
	public String getTripById(){
		try {
			Trip trip = personalServiceImpl.getTripById(tripForm.getId());
			BeanUtils.copyProperties(tripForm,trip);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "success";
	}
	
	@Action(value="gotoDeleteTrip",results={@Result(location="/pages/person/workflow/tripDel.jsp")})
	public String gotoDeleteTrip(){
		return "success";
	}
	
	private RemindForm buildRemindForm(String id,String userId,String msg){
		RemindForm form=new RemindForm();
		form.setObjId(id);
		form.setObjClassName("StopTrip");
		form.setName(msg);
		form.setSendDate(new Date());
		form.setRemindUser(userId);
		form.setHandleState(0);
		return form;
	}

	public IPersonService getPersonalServiceImpl() {
		return personalServiceImpl;
	}

	public void setPersonalServiceImpl(IPersonService personalServiceImpl) {
		this.personalServiceImpl = personalServiceImpl;
	}

	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}

	public TripForm getTripForm() {
		return tripForm;
	}

	public void setTripForm(TripForm tripForm) {
		this.tripForm = tripForm;
	}

	public List<TripForm> getTripListData() {
		return tripListData;
	}

	public void setTripListData(List<TripForm> tripListData) {
		this.tripListData = tripListData;
	}

	public Integer getYear() {
		return year;
	}

	public void setYear(Integer year) {
		this.year = year;
	}

	public Integer getMonth() {
		return month;
	}

	public void setMonth(Integer month) {
		this.month = month;
	}

	public Integer getState() {
		return state;
	}

	public void setState(Integer state) {
		this.state = state;
	}

	public IRemindService getRemindService() {
		return remindService;
	}

	public void setRemindService(IRemindService remindService) {
		this.remindService = remindService;
	}

	public UserManagerService getUserManagerService() {
		return userManagerService;
	}

	public void setUserManagerService(UserManagerService userManagerService) {
		this.userManagerService = userManagerService;
	}
	
}
